package bsi.vn.FirstApp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import bsi.vn.Data.CookieData;
import bsi.vn.Data.CustomerData;
import bsi.vn.Data.CustomerSpinnerAdapter;
import bsi.vn.Data.ProvinceData;
import bsi.vn.Data.ProvinceSpinnerAdapter;
import bsi.vn.Data.TicketAdapter;
import bsi.vn.Data.TicketData;
import bsi.vn.Lib.Consts;
import bsi.vn.Lib.ProcessFunc;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemClickListener;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;

public class TicketSearchActivity extends Activity {
	private final ArrayList<TicketData> glo_arTicket = new ArrayList<TicketData>();
	private View glo_vSearchCondition;
	private View glo_vResult;
	private Button glo_btSearch;
	private EditText glo_edFrom;
	private EditText glo_edTo;
	private EditText glo_edTicketNo;
	private EditText glo_edSerialNo;
	private EditText glo_edAddress;
	private ImageButton glo_btFrom;
	private ImageButton glo_btTo;
	private ImageButton glo_btDisplaySearch;
	private ListView glo_lvTicketList;
	private String glo_Date;
	private String glo_Month;
	private String glo_Year;
	private Spinner glo_snProvince;
	private Spinner glo_snCustomer;
	private DatePickerDialog glo_DPDFrom = null;
	private DatePickerDialog glo_DPDTo = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ticket_search);
//		getActionBar().setDisplayHomeAsUpEnabled(true);
		
		glo_vSearchCondition = findViewById(R.id.tsllSearchCondition);
		glo_vResult = findViewById(R.id.tsllResult);
		
		glo_edTicketNo = (EditText)findViewById(R.id.tsedTicketNo);
		glo_edSerialNo = (EditText)findViewById(R.id.tsedSerialNo);
		glo_edAddress = (EditText)findViewById(R.id.tsedAddress);
		glo_snProvince = (Spinner)findViewById(R.id.tssnProvince);
		glo_snCustomer = (Spinner)findViewById(R.id.tssnCustomer);
		glo_edFrom = (EditText)findViewById(R.id.tsedFrom);
		glo_edTo = (EditText)findViewById(R.id.tsedTo);
		glo_btFrom = (ImageButton)findViewById(R.id.tsbtFrom);
		glo_btTo = (ImageButton)findViewById(R.id.tsbtTo);
		glo_lvTicketList = (ListView)findViewById(R.id.tslvTicket);
		glo_btDisplaySearch = (ImageButton)findViewById(R.id.tsbtDisplaySearch);
		glo_btSearch = (Button)findViewById(R.id.tsbtSearch);
		
		ArrayAdapter<ProvinceData> proAdapter = new ProvinceSpinnerAdapter(this, R.layout.spinner_row, 
				ProcessFunc.GetProvince(this));
		glo_snProvince.setAdapter(proAdapter);
		
		ArrayAdapter<CustomerData> cusAdapter = new CustomerSpinnerAdapter(this, R.layout.spinner_row, 
				ProcessFunc.GetCustomer(this));
		glo_snCustomer.setAdapter(cusAdapter);
		
		glo_btFrom.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Calendar loc_calendar = null;
				String loc_preDateFrom = glo_edFrom.getText().toString();
	          
				if(loc_preDateFrom != null && !loc_preDateFrom.equals("")){
					StringTokenizer st = new StringTokenizer(loc_preDateFrom,"/");
					glo_Date = st.nextToken();
					glo_Month = st.nextToken();
					glo_Year = st.nextToken();
					if(glo_DPDFrom == null)
						glo_DPDFrom = new DatePickerDialog(v.getContext(), new PickDateFrom(),Integer.parseInt(glo_Year),
	                                   Integer.parseInt(glo_Month) - 1, Integer.parseInt(glo_Date));
					glo_DPDFrom.updateDate(Integer.parseInt(glo_Year), Integer.parseInt(glo_Month) - 1, Integer.parseInt(glo_Date));
	                  
				} else {
					loc_calendar = Calendar.getInstance();
					if(glo_DPDFrom == null)
						glo_DPDFrom = new DatePickerDialog(v.getContext(),new PickDateFrom(),loc_calendar.get(Calendar.YEAR),loc_calendar.get(Calendar.MONTH),
	        			   loc_calendar.get(Calendar.DAY_OF_MONTH));
					glo_DPDFrom.updateDate(loc_calendar.get(Calendar.YEAR),loc_calendar.get(Calendar.MONTH),loc_calendar.get(Calendar.DAY_OF_MONTH));
				}
				glo_DPDFrom.show();
			}
		});
		
		glo_btTo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Calendar loc_calendar = null;
				String loc_preDateTo = glo_edTo.getText().toString();
	          
				if(loc_preDateTo != null && !loc_preDateTo.equals("")){
					StringTokenizer st = new StringTokenizer(loc_preDateTo,"/");
					glo_Date = st.nextToken();
					glo_Month = st.nextToken();
					glo_Year = st.nextToken();
					if(glo_DPDTo == null)
						glo_DPDTo = new DatePickerDialog(v.getContext(), new PickDateTo(),Integer.parseInt(glo_Year),
	                                   Integer.parseInt(glo_Month)-1, Integer.parseInt(glo_Date));
					glo_DPDTo.updateDate(Integer.parseInt(glo_Year), Integer.parseInt(glo_Month)-1 , Integer.parseInt(glo_Date));
	                  
				} else {
					loc_calendar = Calendar.getInstance();
					if(glo_DPDTo == null)
						glo_DPDTo = new DatePickerDialog(v.getContext(),new PickDateTo(),loc_calendar.get(Calendar.YEAR),loc_calendar.get(Calendar.MONTH),
	        			   loc_calendar.get(Calendar.DAY_OF_MONTH));
					glo_DPDTo.updateDate(loc_calendar.get(Calendar.YEAR),loc_calendar.get(Calendar.MONTH),loc_calendar.get(Calendar.DAY_OF_MONTH));
				}
				glo_DPDTo.show();
			}
		});
		
		glo_btDisplaySearch.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				glo_vResult.setVisibility(View.INVISIBLE);
				glo_vSearchCondition.setVisibility(View.VISIBLE);
			}
		});
		
		glo_btSearch.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				glo_vResult.setVisibility(View.VISIBLE);
				glo_vSearchCondition.setVisibility(View.INVISIBLE);
				
				myATTicketSearch myTicketSearch = new myATTicketSearch();
				myTicketSearch.execute();
			}
		});
		
	}
	
	public class PickDateFrom implements DatePickerDialog.OnDateSetListener {
	    @Override
	    public void onDateSet(DatePicker view, int year, int monthOfYear,
	            int dayOfMonth) {
	        view.updateDate(year, monthOfYear, dayOfMonth);
	        glo_edFrom.setText(ProcessFunc.VNFormatDate(year, monthOfYear+1, dayOfMonth));
	        glo_DPDFrom.hide();
	    }
	}
	
	public class PickDateTo implements DatePickerDialog.OnDateSetListener {
	    @Override
	    public void onDateSet(DatePicker view, int year, int monthOfYear,
	            int dayOfMonth) {
	        view.updateDate(year, monthOfYear, dayOfMonth);
	        glo_edTo.setText(ProcessFunc.VNFormatDate(year, monthOfYear+1, dayOfMonth));
	        glo_DPDTo.hide();
	    }
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		return false;
	}

	private class myATTicketSearch extends AsyncTask<String, String, String>    {
    	@Override 	
		protected String doInBackground(String... params) {
			String loc_sTicketNo = glo_edTicketNo.getText().toString();
			String loc_sSerialNo = glo_edSerialNo.getText().toString();
			String loc_sAddress = glo_edAddress.getText().toString();
			int loc_iProvince = ((ProvinceData)(glo_snProvince.getSelectedItem())).getId();
			int loc_iCustomer = ((CustomerData)(glo_snCustomer.getSelectedItem())).getId();
    		String loc_dFrom = glo_edFrom.getText().toString();
    		String loc_dTo = glo_edTo.getText().toString();
    		return GetTicket(TicketSearchActivity.this, loc_sTicketNo, loc_sSerialNo, loc_sAddress, loc_iProvince, loc_iCustomer,loc_dFrom,loc_dTo);
		}
		
		@Override
		protected void onPostExecute(String result) {
			String loc_arResponse[] = result.split("\\|");
			TicketData loc_tTicket = new TicketData();
			int loc_iResponseCode = Integer.parseInt(loc_arResponse[0]);
			if (loc_iResponseCode == Consts.RC_LOGOUT)
			{
				startActivity(new Intent(TicketSearchActivity.this, LoginActivity.class));
				return;
			}
			if (loc_iResponseCode == Consts.RC_ERROR)
			{
				ProcessFunc.ShowSimpleDialog(TicketSearchActivity.this, "Error", loc_arResponse[1]);
				return;
			}
			try{
				JSONArray jArray = new JSONArray(loc_arResponse[1]);
				for(int i=0;i<jArray.length();i++){
					JSONObject json_data = jArray.getJSONObject(i);
					loc_tTicket = new TicketData();
					loc_tTicket.setTicketId(json_data.getInt(Consts.SDB_TICKETID));
					loc_tTicket.setTicketCode(json_data.getString(Consts.SDB_TICKETCODE));
					loc_tTicket.setATMId(json_data.getInt(Consts.SDB_ATMID));
					loc_tTicket.setSerialNo(json_data.getString(Consts.SDB_SERIALNO));
					loc_tTicket.setProvince(json_data.getString(Consts.SDB_PROVINCE));
	        		glo_arTicket.add(loc_tTicket);
				}
			}
			catch(JSONException e){
				Log.e("log_tag", "Error parsing data "+e.toString());
			}
			
			glo_lvTicketList.setAdapter(new TicketAdapter(TicketSearchActivity.this, glo_arTicket));
	        
	        glo_lvTicketList.setOnItemClickListener(new OnItemClickListener() {
    			@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    				int TicketId = glo_arTicket.get(position).getTicketId();
    				Intent i = new Intent(getApplicationContext(), TicketDetailActivity.class);
    				i.putExtra("TicketId", TicketId);
    	            startActivity(i);
    			}
    		});
    	}
		
        @Override
        protected void onPreExecute() {
       }
        
        @Override
        protected void onProgressUpdate(String... text) {
        }
 	}
	
	private String GetTicket(Context context, String ticketno, String serialno, String address, int province, int customer, String from, String to) {
    	InputStream is = null;
    	String result = "";
    	try{
    		HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(Consts.MAIN_URL);
        
            CookieData cookie = ProcessFunc.GetCookie(context);
            
            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(10);
            nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC, Consts.F_TICKETSEARCH));
            nameValuePair.add(new BasicNameValuePair(Consts.V_USERID,String.valueOf(cookie.getUserId())));
            nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE,cookie.getCookie()));
            nameValuePair.add(new BasicNameValuePair(Consts.V_TICKETNO,ticketno));
            nameValuePair.add(new BasicNameValuePair(Consts.V_SERIAL,serialno));
            nameValuePair.add(new BasicNameValuePair(Consts.V_ADDRESS,address));
            nameValuePair.add(new BasicNameValuePair(Consts.V_PROVINCE, String.valueOf(province)));
            nameValuePair.add(new BasicNameValuePair(Consts.V_CUSTOMER,String.valueOf(customer)));
            nameValuePair.add(new BasicNameValuePair(Consts.V_FROM,from));
            nameValuePair.add(new BasicNameValuePair(Consts.V_TO,to));
           
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
    		is = entity.getContent();

    		BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),16);
	    	StringBuilder sb = new StringBuilder();
	    	String line = null;
	    	while ((line = reader.readLine()) != null) {
	    		sb.append(line + "\n");
	    	}
	    	is.close();
	    	result = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	} 
}
